//
//  AppDelegate.swift
//  rryproject
//
//  Created by zhengyi on 2018/1/11.
//  Copyright © 2018年 inesv. All rights reserved.
//

import UIKit
import SVProgressHUD
import UserNotifications
import ObjectMapper

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, JPUSHRegisterDelegate {

    var window: UIWindow?


    // MARK: - AppLifeCycle
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        self.window?.backgroundColor = UIColor.white
        
        SVProgressHUD.setForegroundColor(R_UIThemeColor)
        
        //todo:注册推送平台推送功能
        let entity = JPUSHRegisterEntity()
        entity.types = Int(JPAuthorizationOptions.alert.rawValue) | Int(JPAuthorizationOptions.sound.rawValue) | Int(JPAuthorizationOptions.badge.rawValue)
        JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self)
        JPUSHService.setup(withOption: launchOptions, appKey: ConstAPI.JPushAppKey, channel: "Publish channel", apsForProduction: false)
        
        NotificationCenter.default.addObserver(self, selector: #selector(networkDidReceiveMessage(notification:)), name: NSNotification.Name.jpfNetworkDidReceiveMessage, object: nil)
        /*
        if #available(iOS 10.0, *) {
            let notifiCenter = UNUserNotificationCenter.current()
            notifiCenter.delegate = self
            notifiCenter.requestAuthorization(options: [.alert,.badge,.sound], completionHandler: { (flag, error) in
                if flag {
                    Tools.DLog(message: "iOS 10 request notification success")
                } else {
                    Tools.DLog(message: "iOS 10 request notification fail")
                }
            })
            
        }*/
//        SQLiteManager.shareInstance.connectCreatTalbe(dbName: "rry_wallet")

        self.setLoginStatus()

        switchToLoginController()

        
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
    
    // MARK: -JPUSHRegisterDelegate
    // iOS 10.x 需要
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {
        
        let userInfo = notification.request.content.userInfo;
        if notification.request.trigger is UNPushNotificationTrigger {
            JPUSHService.handleRemoteNotification(userInfo);
        }
        completionHandler(Int(UNNotificationPresentationOptions.alert.rawValue))
    }
    
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
        
        let userInfo = response.notification.request.content.userInfo;
        if response.notification.request.trigger is UNPushNotificationTrigger {
            JPUSHService.handleRemoteNotification(userInfo);
        }
        completionHandler();
        // 应用打开的时候收到推送消息
        //NotificationCenter.default.post(name: NSNotification.Name(rawValue: NotificationName_ReceivePush), object: NotificationObject_Sueecess, userInfo: userInfo)
    }
    
    
    // MARK: - Private Method
    func registerAppNotificationSettings(launchOptions: [UIApplicationLaunchOptionsKey: Any]?) {
        if #available(iOS 10.0, *) {
            
            let notifiCenter = UNUserNotificationCenter.current()
            notifiCenter.delegate = self
            notifiCenter.requestAuthorization(options: [.alert,.badge,.sound], completionHandler: { (flag, error) in
                if flag {
                    Tools.DLog(message: "iOS 10 request notification success")
                    
                } else {
                    Tools.DLog(message: "iOS 10 request notification fail")
                }
            })
            
        } else {
            
            let setting = UIUserNotificationSettings.init(types: [.alert, .badge, .sound], categories: nil)
            UIApplication.shared.registerUserNotificationSettings(setting)
            
        }
        UIApplication.shared.registerForRemoteNotifications()
        
    }
    
    //iOS10:处理前台收到通知的代理方法
    /*
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        Tools.DLog(message: "\(userInfo)")
        
        if (notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))! {
            
            //UMessage.didReceiveRemoteNotification(userInfo)
            
            
        } else {
            
        }
        completionHandler([.sound, .alert, .badge])
        
        
    }
    
    //iOS10:处理后台点击通知的代理方法
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        Tools.DLog(message: "\(userInfo)")
        
        UIApplication.shared.applicationIconBadgeNumber = 0
        
        if (response.notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))! {
            
            //UMessage.didReceiveRemoteNotification(userInfo)
            
            if let type = userInfo["type"] {
                let typestr = type as! String
                if typestr == "1" {
                }
            }
        } else {
            
        }
        
        completionHandler()
        
    }*/
    
    //iOS8和iOS9通知处理
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        Tools.DLog(message: "\(userInfo)")
        
        JPUSHService.handleRemoteNotification(userInfo)
        completionHandler(UIBackgroundFetchResult.newData)
        
        if application.applicationState == .active {
            //前台接收到消息
            if let type = userInfo["type"] {
                let typestr = type as! String
                if typestr == "1" {
                   
                }
            }
        } else {
            //后台接收到消息
            if let type = userInfo["type"] {
                let typestr = type as! String
                if typestr == "1" {
                }
            }
            UIApplication.shared.applicationIconBadgeNumber = 0
            
        }
        completionHandler(.newData)
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        
        let devicedata = deviceToken as NSData
        let string = devicedata.description.replacingOccurrences(of: "<", with: "").replacingOccurrences(of: " ", with: "").replacingOccurrences(of: ">", with: "")
        JPUSHService.registerDeviceToken(deviceToken)

        Tools.DLog(message: "register success \(string)")
    }
    
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        
        Tools.DLog(message: "register fail \(error)")
    }
    
    func setLoginStatus() {
        
        let login = UserDefaults.standard.value(forKey: "hadLogin") as? Bool
        if login == nil {
            UserDefaults.standard.setValue(false, forKey: "hadLogin")
        }
        UserDefaults.standard.synchronize()
    }
    
    func switchToLoginController() {
        
    
        let hadlogin = UserDefaults.standard.value(forKey: "hadLogin") as? Bool
        if hadlogin! {
            let token = UserDefaults.standard.value(forKey: "token")
            if token == nil {
                let loginvc = LoginViewController()
                let loginNav = TPNavigationController.init(rootViewController: loginvc)
                window?.rootViewController = loginNav
            } else {
               relogin()
            }
            
        } else {
            let preloginvc = PreLoginViewController()
            let preloginNav = TPNavigationController.init(rootViewController: preloginvc)
           window?.rootViewController = preloginNav
        }
        
        /*
        let walletvc = WalletViewController()
        let preloginNav = TPNavigationController.init(rootViewController: walletvc)
        window?.rootViewController = preloginNav*/
    }
    
    func networkDidReceiveMessage(notification:NSNotification) {
    
        //服务端传递的Extras附加字段，key是自己定义的
        let userInfo = notification.userInfo
        let content = userInfo!["content"]
        let extras = userInfo!["extras"]
    }
    
    func relogin() {
        
        let token = UserDefaults.standard.value(forKey: "token") as! String
        let params = ["token" : token]
        NetWorkTool.requestData(.post, URLString: ConstAPI.kAPIRelogin, parameters: params, showIndicator: false, success: { (jsonObjc) in
            let result = Mapper<LoginResponse>().map(JSONObject: jsonObjc)
            if let code = result?.code {
                if code == 200 {
                    SingleTon.shared.userInfo = result?.data
                    SingleTon.shared.userInfo?.token = token
                    Tools.switchToWalletViewController()
                } else {
                    Tools.switchToLoginViewController()
                }
            } else {
                Tools.switchToLoginViewController()
            }
        }) { (error) in
            Tools.switchToLoginViewController()
        }
        
    }


}

